import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/model/questions_model.dart';
import 'package:appflutterhomeschool/model/student_information_model.dart';
import 'package:appflutterhomeschool/route/application.dart';
import 'package:appflutterhomeschool/route/routes.dart';
import 'package:appflutterhomeschool/ui/dialogs/prompt_dialog_widgets.dart';
import 'package:appflutterhomeschool/ui/pages/notice/new_form/add_question_type_page.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';
import '../my_app_view_model.dart';

///用户： ninetailedfox
///时间： 2020/7/19
///邮箱： 1037438704@qq.com
///功能： 创建表单状态管理器
class NewFormViewModel extends ChangeNotifier {
  MyAppViewModel myAppViewModel;

  //表单集合
  List<QuestionsModel> questionsModelList = [];
  BuildContext me;
  List<StudentModel> studentList;
  TextEditingController titleText = TextEditingController();
  TextEditingController textContent = TextEditingController();

  NewFormViewModel(this.me);

  initView() {
    myAppViewModel = Provider.of(me);
  }

  String student = "";

  initEvent(int tag) {
    switch (tag) {
      case 0:
        //添加收件人
        Application()
            .navigatePushToPage(me, Routes.recipientListPage, {}).then((value) {
          if (value != null) {
            studentList = value["list"];
            student = "";
            studentList.forEach((element) {
              student = "$student${element.name},";
            });
            student = student.substring(0, student.length - 1);
            notifyListeners();
          }
        });
        break;
    }
  }

  releaseOnTap() {
    Map<String, dynamic> mapJson = {
      "form_notification":{
        "receiver": studentList.toList(),
        //类型：String  必有字段  备注：标题
        "title": titleText.text,
        "msg": textContent.text,
        "sender_type": 'Teacher',
        //类型：String  必有字段  备注：发送者类型（默认Teacher）
        "receiver_type": "Student",
        //类型：String  必有字段  备注：接收者类型（默认为Student）
        "cls_mapping": myAppViewModel.studentInformationModel.classMappingId,
        "notification_type": "Form",
      },
      "questions": questionsModelList.toList(),
    };
    Logger().d(mapJson);
    Dio2Utils.getInstance().post(ApiService.createForm, mapJson,
        (successCallBack) {
      Fluttertoast.showToast(msg: successCallBack["message"]);
      Navigator.pop(me);
    }, (errorCallBack) {
      Fluttertoast.showToast(msg: errorCallBack);
    });
  }

  addItem() {
    PromptDialogWidgets(me).formSwitchButtomDialog(valueChanged: (index) {
      Application().navigatePushToPage(me, Routes.addQuestionTypePage, {
        "pageTag": index,
        "getIndex": questionsModelList.length
      }).then((value) {
        if (value != null) {
          Logger().d(value);
          questionsModelList.add(QuestionsModel.fromJson(value));
          notifyListeners();
        }
      });
    });
  }

  //编辑  删除
  editOnTap(index) {
    Navigator.push(
        me,
        MaterialPageRoute(
            builder: (context) => AddQuestionTypePage(
                  questionsModel: questionsModelList[index],
                ))).then((value) {
      if (value != null) {
        questionsModelList[index] = QuestionsModel.fromJson(value);
        notifyListeners();
      }
    });
    notifyListeners();
  }

  deleteOnTap(index) {
    questionsModelList.removeAt(index);
    notifyListeners();
  }
}
